/**
 * Created by Administrator on 14-6-18.
 */
var models = require('./models') ;    // 导入自定义组件
var Cp = models.cp;
var Sds = models.sds;
var Sps = models.sps;
var EventProxy = require('eventproxy');
var Paginate = require('./Paginate');

/**
 * 分页列出产品信息
 * @param condition 条件
 * @param page  当前页
 * @param perPage 每页记录
 * @param opt 排序,skip,limit...
 * @param callback
 *  - err
 *  - Paginate
 */

var listProductAndPaginate = function (condition,page,perPage,opt,callback){
    if(!condition){
        condition = {};
    }
    if(!opt){
        opt = {};
    }
    //计算分页信息
    if(!perPage || perPage < 1){
        perPage = 20;
    }
    var skip = 0;
    if(page && page > 1){
        skip = (page-1) * perPage;
    }
    opt['skip'] = skip;
    opt['limit'] = perPage;
    var ep = new EventProxy();
    ep.fail(callback);
    ep.all('total','products',function(total,products){
        var paginate = new Paginate(page,perPage,total,products);
        callback(null,paginate);
    });
    //计算总数
    Cp.count(condition,ep.done('total'));
    //查询当前页产品信息
    Cp.find(condition,{'sn':1,'pn':1,'cd':1,'ds':1,'bn':1,'tp':1,'isd':1,'isqp':1,'iswa':1,'war':1,'osd':1,'oswa':1,'na':1,'bp':1},opt,ep.done('products'));
};
/**
 * 分页查看所有产品信息
 */
exports.getPcAll = function(req,res,next){
    var pageNum = req.body.pageNum;
    var numPerPage = req.body.numPerPage;
    if(pageNum =='undefined' || numPerPage =='undefined'){
        pageNum = 1;
        numPerPage = 20;
    }
    var condition = {};
    var sn = req.body.psn;
    var pn = req.body.pname;
    var tp = req.body.ptype;
    var ds = req.body.pds;
    if(sn || pn || tp || ds){
        condition = {sn : new RegExp(sn),pn : new RegExp(pn), tp : new RegExp(tp), ds: new RegExp(ds)};
    }
    listProductAndPaginate(condition,pageNum,numPerPage,{sort:{_id:-1}},function(err,paginate){
        if(err){
            next(err);
        }else{
            if(!paginate){
                res.send('没有数据！');
            }else{
                var page = paginate.page;
                var perPage = paginate.perPage;
                var total = paginate.total;
                var items = paginate.items;
                //var pages = paginate.pages;
                //var currentPageTotal = paginate.currentPageTatol;
                //var hasNextPage = paginate.hasNextPage();
                //var nextPage = paginate.nextPage();
                //var hasPrevPage = paginate.hasPrevPage();
                //var prevPage = paginate.prevPage();
                //res.render('pclist',{cps : items,page : page,perPage : perPage,total : total,
                //    currentPageTotal : currentPageTotal,hasNextPage : hasNextPage,nextPage : nextPage,
                //   hasPrevPage : hasPrevPage,pervPage : prevPage,pages : pages});
                res.render('pclist',{cps : items,page : page,perPage : perPage,total : total,sn:sn,pn:pn,tp:tp,ds:ds});
            }
        }
    });
};
/**
 * 添加产品信息
 * @param req
 * @param res
 */
exports.addPcUi = function(req,res){
    res.render('add_product');
};
function getSds(req){
    var trleng = req.body.trleng;
    var psk1 = req.body.psk1;
    var psv1 = req.body.psv1;
    var sdArray = new Array();
    if(psk1 != "" && psv1 != ""){
        var newSds = new Sds({
            sk : psk1,
            sv : psv1
        });
        sdArray.push(newSds);
        if(trleng > 1){
            for(var i=2;i<=trleng;i++){
                var newSds2 = new Sds({
                    sk : req.param('psk'+i),
                    sv : req.param('psv'+i)
                });
                sdArray.push(newSds2);
            }
        }
    }
    return sdArray;
};
function getSps(req){
    var spstrleng = req.body.spstrleng;
    var ppk1 = req.body.ppk1;
    var ppv1 = req.body.ppv1;
    var spArray = new Array();
    if(ppk1 !="" && ppv1 !=""){
        var newSps = new Sps();
        newSps.pk = ppk1;
        newSps.pv = ppv1;
        spArray.push(newSps);
        if(spstrleng > 1){
            for(var j=2;j<=spstrleng;j++){
                var newSps2 = new Sps({
                    pk : req.param('ppk'+j),
                    pv : req.param('ppv'+j)
                });
                spArray.push(newSps2);
            }
        }
    }
    return spArray;
};
exports.addPc = function(req,res){
    var sdArray = getSds(req);
    var spArray = getSps(req);
    var newCp = new Cp({
        sn : req.body.psn,
        pn : req.body.pName,
        cd : req.body.pcd,
        ds : req.body.pds,
        bn : req.body.pbn,
        tp : req.body.pType,
        isd : req.body.pisd,
        isqp : req.body.pisqp,
        iswa : req.body.piswa,
        war : req.body.pwar,
        osd : req.body.posd,
        oswa : req.body.poswa,
        na : req.body.pna,
        bp : req.body.pbp,
        sds : sdArray,
        sps : spArray
    });
    newCp.save(function(err){
        if (err) {
            res.send('{"statusCode":"300","message":"操作失败,该产品可能已经存在！"}');
        }else{
            res.send('{"statusCode":"200","message":"操作成功!","navTabId":"pcList","forwardUrl":"", "callbackType":"closeCurrent"}');
        };
    })
};
/**
 * 删除产品信息
 */
exports.deleteProductOne = function(req,res){
    var pid = req.param('pid');
    Cp.remove({_id : pid},function(err){
        if (err) {
            res.send('{"statusCode":"300","message":"操作失败!"}');
        }else{
            res.send('{"statusCode":"200","message":"操作成功!","navTabId":"pcList","forwardUrl":""}');
        };
    });
};
/**
 * 批量删除
 */
exports.deleteProductBatch = function(req,res){
    var pids = req.param('ids');
    Cp.remove({_id : {$in : pids.split(',')}},function(err){
        if (err) {
            res.send('{"statusCode":"300","message":"操作失败!"}');
        }else{
            res.send('{"statusCode":"200","message":"操作成功!","navTabId":"pcList","forwardUrl":""}');
        };
    });
};
/**
 * 修改产品信息
 * @param req
 * @param res
 */
exports.updateProductUi = function(req,res){
    var pid = req.param('pid');
    Cp.findById(pid,{'sn':1,'pn':1,'cd':1,'ds':1,'bn':1,'tp':1,'isd':1,'isqp':1,'iswa':1,'war':1,'osd':1,'oswa':1,'na':1,'bp':1,'sds':1,'sps':1},function(err,doc){
        res.render('update_product',{cp : doc,sds : doc.sds,sps : doc.sps});
    });
};
exports.updateProductOne = function(req,res){
    var pid = req.body.pid;
    var sdArray = getSds(req);
    var spArray = getSps(req);
    var psn = req.body.psn;
    var pName = req.body.pName;
    var pcd = req.body.pcd;
    var pds = req.body.pds;
    var pbn = req.body.pbn;
    var pType = req.body.pType;
    var pisd = req.body.pisd;
    var pisqp = req.body.pisqp;
    var piswa = req.body.piswa;
    var pwar = req.body.pwar;
    var posd = req.body.posd;
    var poswa = req.body.poswa;
    var pna = req.body.pna;
    var pbp = req.body.pbp;
    Cp.findById(pid,function(err,doc){
        doc.sds.pull();
        doc.sps.pull();
        doc.sn = psn;
        doc.pn = pName;
        doc.cd = pcd;
        doc.ds = pds;
        doc.bn = pbn;
        doc.tp = pType;
        doc.isd = pisd;
        doc.isqp = pisqp;
        doc.iswa = piswa;
        doc.war = pwar;
        doc.osd = posd;
        doc.oswa = poswa;
        doc.na = pna;
        doc.bp = pbp;
        doc.sds = sdArray;
        doc.sps = spArray;
        doc.save(function(err){
            if(err){
                res.send('{"statusCode":"300","message":"操作失败!"}');
            }else{
                res.send('{"statusCode":"200","message":"操作成功!","navTabId":"pcList","callbackType":"closeCurrent","forwardUrl":""}');
            }
        });
    });
};
/**
 * 查看产品更多信息
 * @param req
 * @param res
 */
exports.getPcMore = function(req,res){
    var cpid = req.param('pid');
    Cp.findOne({_id:cpid},{'mrs':1,'sds':1,'sps':1},function(err,doc){
        if(err){
            res.send('{"statusCode":"300","message":"操作失败!"}');
        }else{
            res.render('cpmore',{pid : doc._id, mrs : doc.mrs, sds : doc.sds, sps : doc.sps});
        }
    });
};
/**
 * 添加维修记录
 * @param req
 * @param res
 */
exports.addMrUI = function(req,res){
    var pid = req.param('pid');
    res.render('add_mr',{pid : pid});
};
exports.addMr = function(req,res){
    var pid = req.body.pid;
    var mrdate = req.body.mrdate;
    var mrep = req.body.mrep;
    var mrwa = req.body.mrwa;
    var mrqp = req.body.mrqp;
    var mrcon = req.body.mrcon;
    Cp.findById(pid,function(err,doc){
        doc.mrs.push({md:mrdate, me:mrep, mqp:mrqp, mwa:mrwa, con:mrcon});
        doc.save(function(err){
            if (err) {
                res.send('{"statusCode":"300","message":"操作失败!"}');
            }else{
                res.send('{"statusCode":"200","message":"操作成功!","navTabId":"dlg_cpmore","forwardUrl":"getCpMorePost?pid='+pid+'"}');
            };
        });
    });
};
exports.deleteMrOne = function(req,res){
    var mrId = req.param('mrid');
    var pid = req.param('pid');
    Cp.findById(pid,function(err,doc){
        doc.mrs.pull({_id:mrId});
        doc.save(function(err){
            if (err) {
                res.send('{"statusCode":"300","message":"操作失败!"}');
            }else{
                res.send('{"statusCode":"200","message":"操作成功!","navTabId":"dlg_cpmore","forwardUrl":"getCpMorePost?pid='+pid+'"}');
            };
        });
    });
};
/**
 * 批量添加产品信息
 * @param req
 * @param res
 */
exports.batchAddPcUi = function(req,res){
    res.render('batch_add_product');
};
exports.batchAddPc = function(req,res){
    var sn1 = req.body.psn1;
    var sn2 = req.body.psn2;
    var sdArray = getSds(req);
    var spArray = getSps(req);
    var pcArray = new Array();
    for(var i = sn1; i <= sn2; i++){
        var newCp = new Cp({
            sn : i,
            pn : req.body.pName,
            cd : req.body.pcd,
            ds : req.body.pds,
            bn : req.body.pbn,
            tp : req.body.pType,
            isd : req.body.pisd,
            isqp : req.body.pisqp,
            iswa : req.body.piswa,
            war : req.body.pwar,
            osd : req.body.posd,
            oswa : req.body.poswa,
            na : req.body.pna,
            bp : req.body.pbp,
            sds : sdArray,
            sps : spArray
        });
        pcArray.push(newCp);
    }
    Cp.create(pcArray,function(err){
        if (err) {
            res.send('{"statusCode":"300","message":"操作失败  请检查是否有SN已存在！"}');
        }else{
            res.send('{"statusCode":"200","message":"操作成功!","navTabId":"pcList","forwardUrl":"", "callbackType":"closeCurrent"}');
        };
    });
};
//批量生成二维码
exports.makeBarcode = function(req,res){
    var pids = req.param('ids').toString();
    Cp.find({_id : {$in : pids.split(',')}},{'sn':1,'tp':1,'pn':1},function(err,docs){
        res.render('barcode_all',{sns : docs});
    });
};
